/**
 * 图像标注绘制工具
 * 支持矩形、点标注等多种标注模式
 * 处理类别颜色、层级管理、标注完成回调等功能
 */

import { ref, reactive, nextTick } from 'vue'

export function useAnnotationDrawer() {
  // 当前标注模式
  const annotationMode = ref('rectangle')
  // 当前选中的类别
  const currentCategory = ref(null)
  // 线条宽度
  const lineWidth = ref(2)
  // 所有标注数据
  const annotations = ref([])
  // 当前正在绘制的标注
  const currentDrawing = ref(null)
  // 绘制状态
  const isDrawing = ref(false)
  // 标注层级计数器
  const zIndexCounter = ref(1)
  
  // 图像容器和相关元素
  let imageContainer = null
  let imageElement = null
  let overlayElement = null
  
  /**
   * 将十六进制颜色转换为rgba
   * @param {string} hex - 十六进制颜色
   * @param {number} alpha - 透明度 (0-1)
   * @returns {string} rgba颜色字符串
   */
  const hexToRgba = (hex, alpha = 0.2) => {
    const r = parseInt(hex.slice(1, 3), 16)
    const g = parseInt(hex.slice(3, 5), 16)
    const b = parseInt(hex.slice(5, 7), 16)
    return `rgba(${r}, ${g}, ${b}, ${alpha})`
  }
  
  /**
   * 初始化标注绘制器
   * @param {HTMLElement} container - 图像容器元素
   * @param {HTMLImageElement} image - 图像元素
   */
  const initialize = (container, image) => {
    imageContainer = container
    imageElement = image
    
    // 创建或获取标注覆盖层
    overlayElement = container.querySelector('.annotation-overlay')
    if (!overlayElement) {
      overlayElement = document.createElement('div')
      overlayElement.className = 'annotation-overlay'
      overlayElement.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        z-index: 10;
      `
      container.appendChild(overlayElement)
    }
    
    // 添加事件监听器
    setupEventListeners()
  }
  
  /**
   * 设置事件监听器
   */
  const setupEventListeners = () => {
    if (!imageContainer) return
    
    // 启用容器的鼠标事件
    imageContainer.style.pointerEvents = 'auto'
    
    // 使用捕获阶段确保事件能够正确处理
    imageContainer.addEventListener('mousedown', handleMouseDown, true)
    imageContainer.addEventListener('mousemove', handleMouseMove, false)
    imageContainer.addEventListener('mouseup', handleMouseUp, false)
    imageContainer.addEventListener('dblclick', handleDoubleClick, true)
    
    console.log('[AnnotationDrawer] 事件监听器已设置')
  }
  
  /**
   * 移除事件监听器
   */
  const removeEventListeners = () => {
    if (!imageContainer) return
    
    imageContainer.removeEventListener('mousedown', handleMouseDown, true)
    imageContainer.removeEventListener('mousemove', handleMouseMove, false)
    imageContainer.removeEventListener('mouseup', handleMouseUp, false)
    imageContainer.removeEventListener('dblclick', handleDoubleClick, true)
    
    console.log('[AnnotationDrawer] 事件监听器已移除')
  }
  
  /**
   * 获取相对于图像的坐标
   * @param {MouseEvent} event - 鼠标事件
   * @returns {object} 图像坐标
   */
  const getImageCoordinates = (event) => {
    if (!imageElement) return { x: 0, y: 0 }
    
    const rect = imageElement.getBoundingClientRect()
    const containerRect = imageContainer.getBoundingClientRect()
    
    // 计算相对于容器的坐标
    const x = event.clientX - containerRect.left
    const y = event.clientY - containerRect.top
    
    // 确保坐标在图像范围内
    const imageRect = {
      left: rect.left - containerRect.left,
      top: rect.top - containerRect.top,
      width: rect.width,
      height: rect.height
    }
    
    return {
      x: Math.max(0, Math.min(x - imageRect.left, imageRect.width)),
      y: Math.max(0, Math.min(y - imageRect.top, imageRect.height))
    }
  }
  
  /**
   * 鼠标按下事件处理
   * @param {MouseEvent} event - 鼠标事件
   */
  const handleMouseDown = (event) => {
    console.log('[AnnotationDrawer] 鼠标按下:', annotationMode.value, event.target)
    
    if (!currentCategory.value) {
      console.warn('[AnnotationDrawer] 请先选择一个类别')
      return
    }
    
    // 检查是否点击在现有标注上
    const clickedElement = event.target
    
    // 特殊处理：如果正在绘制点标注且点击的是第一个点，完成绘制
    if (annotationMode.value === 'point' && currentDrawing.value && 
        clickedElement.classList.contains('line-point') && 
        clickedElement.classList.contains('point-0')) {
      console.log('[AnnotationDrawer] 点击第一个点，完成多边形绘制')
      event.preventDefault()
      event.stopPropagation()
      finishLinePolygonDrawing()
      return
    }
    
    const isOnExistingAnnotation = clickedElement.closest('.annotation-shape, .annotation-point') || 
                                   (clickedElement.tagName === 'polygon' && !currentDrawing.value)
    
    if (isOnExistingAnnotation) {
      console.log('[AnnotationDrawer] 点击在现有标注上，跳过')
      return
    }
    
    event.preventDefault()
    event.stopPropagation()
    
    const coords = getImageCoordinates(event)
    console.log('[AnnotationDrawer] 图像坐标:', coords)
    
    switch (annotationMode.value) {
      case 'rectangle':
        startRectangleDrawing(coords)
        break
      case 'point':
        createPointAnnotation(coords)
        break
      case 'select':
        console.log('[AnnotationDrawer] 选择模式，不创建标注')
        break
      default:
        console.log('[AnnotationDrawer] 未知标注模式:', annotationMode.value)
    }
  }
  
  /**
   * 鼠标移动事件处理
   * @param {MouseEvent} event - 鼠标事件
   */
  const handleMouseMove = (event) => {
    if (!isDrawing.value || !currentDrawing.value) return
    
    const coords = getImageCoordinates(event)
    
    switch (annotationMode.value) {
      case 'rectangle':
        updateRectangleDrawing(coords)
        break
    }
  }
  
  /**
   * 鼠标抬起事件处理
   * @param {MouseEvent} event - 鼠标事件
   */
  const handleMouseUp = () => {
    if (!isDrawing.value || annotationMode.value !== 'rectangle') return
    
    finishRectangleDrawing()
  }
  
  /**
   * 双击事件处理（完成点连线绘制）
   * @param {MouseEvent} event - 鼠标事件
   */
  const handleDoubleClick = (event) => {
    console.log('[AnnotationDrawer] 双击事件:', annotationMode.value, currentDrawing.value)
    
    if (annotationMode.value === 'point' && currentDrawing.value) {
      event.preventDefault()
      event.stopPropagation()
      console.log('[AnnotationDrawer] 完成点连线绘制')
      finishLinePolygonDrawing()
    }
  }
  
  /**
   * 开始矩形绘制
   * @param {object} coords - 起始坐标
   */
  const startRectangleDrawing = (coords) => {
    isDrawing.value = true
    currentDrawing.value = {
      id: `annotation_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
      type: 'rectangle',
      categoryId: currentCategory.value.key,
      startX: coords.x,
      startY: coords.y,
      x: coords.x,
      y: coords.y,
      width: 0,
      height: 0,
      zIndex: zIndexCounter.value++,
      color: currentCategory.value.color,
      title: currentCategory.value.title
    }
    
    createAnnotationElement(currentDrawing.value)
  }
  
  /**
   * 更新矩形绘制
   * @param {object} coords - 当前坐标
   */
  const updateRectangleDrawing = (coords) => {
    if (!currentDrawing.value) return
    
    const drawing = currentDrawing.value
    drawing.x = Math.min(drawing.startX, coords.x)
    drawing.y = Math.min(drawing.startY, coords.y)
    drawing.width = Math.abs(coords.x - drawing.startX)
    drawing.height = Math.abs(coords.y - drawing.startY)
    
    updateAnnotationElement(drawing)
  }
  
  /**
   * 完成矩形绘制
   */
  const finishRectangleDrawing = () => {
    if (!currentDrawing.value) return
    
    const drawing = currentDrawing.value
    
    // 检查最小尺寸
    if (drawing.width < 5 || drawing.height < 5) {
      removeAnnotationElement(drawing.id)
      currentDrawing.value = null
      isDrawing.value = false
      return
    }
    
    // 移除临时绘制元素，重新创建完成的矩形元素
    removeAnnotationElement(drawing.id)
    createCompletedRectangleElement(drawing)
    
    // 添加到标注列表
    addAnnotation(drawing)
    
    currentDrawing.value = null
    isDrawing.value = false
  }
  
  
  
  
  /**
   * 创建点标注（作为线段连接的多边形）
   * @param {object} coords - 点击坐标
   */
  const createPointAnnotation = (coords) => {
    console.log('[AnnotationDrawer] 创建点连线标注:', coords)
    
    if (!currentDrawing.value) {
      // 开始新的点连线标注
      currentDrawing.value = {
        id: `annotation_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
        type: 'line-polygon', // 新类型：线段连接的多边形
        categoryId: currentCategory.value.key,
        points: [coords],
        zIndex: zIndexCounter.value++,
        color: currentCategory.value.color,
        title: currentCategory.value.title
      }
      isDrawing.value = true
      console.log('[AnnotationDrawer] 开始新的点连线标注:', currentDrawing.value)
      createLinePolygonElement(currentDrawing.value)
    } else {
      // 添加新点
      currentDrawing.value.points.push(coords)
      console.log('[AnnotationDrawer] 添加点连线点，总点数:', currentDrawing.value.points.length)
      updateLinePolygonElement(currentDrawing.value)
    }
  }
  
  /**
   * 创建标注DOM元素
   * @param {object} annotation - 标注数据
   */
  const createAnnotationElement = (annotation) => {
    if (!overlayElement) return
    
    const element = document.createElement('div')
    element.id = `annotation-${annotation.id}`
    element.className = 'annotation-shape'
    
    element.style.cssText = `
      position: absolute;
      border: ${lineWidth.value}px solid ${annotation.color};
      background: ${hexToRgba(annotation.color, 0.2)};
      box-sizing: border-box;
      pointer-events: auto;
      cursor: pointer;
      z-index: ${annotation.zIndex};
    `
    
    // 添加标签
    const label = document.createElement('div')
    label.className = 'annotation-label'
    label.textContent = annotation.displayText || annotation.title
    label.style.cssText = `
      position: absolute;
      top: -24px;
      left: 0;
      padding: 2px 6px;
      background: ${annotation.color};
      color: white;
      font-size: 12px;
      border-radius: 4px;
      white-space: nowrap;
      user-select: none;
    `
    
    element.appendChild(label)
    overlayElement.appendChild(element)
    
    updateAnnotationElement(annotation)
  }
  
  /**
   * 更新标注DOM元素
   * @param {object} annotation - 标注数据
   */
  const updateAnnotationElement = (annotation) => {
    const element = overlayElement?.querySelector(`#annotation-${annotation.id}`)
    if (!element) return
    
    if (annotation.type === 'rectangle') {
      element.style.left = `${annotation.x}px`
      element.style.top = `${annotation.y}px`
      element.style.width = `${annotation.width}px`
      element.style.height = `${annotation.height}px`
    }
  }
  
  /**
   * 创建完成的矩形元素（带角点）
   * @param {object} annotation - 标注数据
   */
  const createCompletedRectangleElement = (annotation) => {
    if (!overlayElement) return
    
    const container = document.createElement('div')
    container.id = `annotation-${annotation.id}`
    container.className = 'annotation-rectangle-completed'
    container.style.cssText = `
      position: absolute;
      left: ${annotation.x}px;
      top: ${annotation.y}px;
      width: ${annotation.width}px;
      height: ${annotation.height}px;
      z-index: ${annotation.zIndex};
      /* 容器本身不捕获事件，但允许其子元素（如角点）捕获 */
      pointer-events: none; 
    `
    
    // 主矩形区域
    const rect = document.createElement('div')
    rect.className = 'annotation-rect annotation-shape'
    const backgroundFill = hexToRgba(annotation.color, 0.2)
    
    rect.style.cssText = `
      width: 100%;
      height: 100%;
      border: ${lineWidth.value}px solid ${annotation.color};
      background: ${backgroundFill};
      box-sizing: border-box;
      /* 图形本身不捕获事件，允许在其上开始新绘制 */
      pointer-events: none; 
    `
    
    // 添加四个角点
    const corners = [
      { x: -4, y: -4 }, // 左上角
      { x: annotation.width - 4, y: -4 }, // 右上角
      { x: annotation.width - 4, y: annotation.height - 4 }, // 右下角
      { x: -4, y: annotation.height - 4 } // 左下角
    ]
    
    corners.forEach((corner, index) => {
      const point = document.createElement('div')
      point.className = `annotation-corner corner-${index}`
      point.style.cssText = `
        position: absolute;
        left: ${corner.x}px;
        top: ${corner.y}px;
        width: 8px;
        height: 8px;
        background: white;
        border: 2px solid ${annotation.color};
        border-radius: 50%;
        cursor: pointer;
        z-index: 1;
        /* 角点需要能被点击 */
        pointer-events: auto; 
      `
      container.appendChild(point)
    })
    
    // 添加标签
    const label = document.createElement('div')
    label.className = 'annotation-label'
    label.textContent = annotation.displayText || annotation.title
    label.style.cssText = `
      position: absolute;
      top: -24px;
      left: 0;
      padding: 2px 6px;
      background: ${annotation.color};
      color: white;
      font-size: 12px;
      border-radius: 4px;
      white-space: nowrap;
      user-select: none;
      pointer-events: none;
    `
    
    container.appendChild(rect)
    container.appendChild(label)
    overlayElement.appendChild(container)
    
    console.log('[AnnotationDrawer] 完成矩形元素已创建:', annotation.id)
  }
  
  
  
  
  /**
   * 创建线段多边形元素
   * @param {object} annotation - 标注数据
   */
  const createLinePolygonElement = (annotation) => {
    if (!overlayElement) return
    
    const container = document.createElement('div')
    container.id = `annotation-${annotation.id}`
    container.className = 'annotation-line-polygon'
    container.style.cssText = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: ${annotation.zIndex};
    `
    
    // 创建SVG元素
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    svg.style.cssText = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
    `
    
    container.appendChild(svg)
    overlayElement.appendChild(container)
    
    updateLinePolygonElement(annotation)
  }
  
  /**
   * 更新线段多边形元素
   * @param {object} annotation - 标注数据
   */
  const updateLinePolygonElement = (annotation) => {
    const container = overlayElement?.querySelector(`#annotation-${annotation.id}`)
    const svg = container?.querySelector('svg')
    if (!container || !svg) return
    
    // 清除现有内容
    svg.innerHTML = ''
    
    // 移除现有的点元素
    container.querySelectorAll('.line-point').forEach(el => el.remove())
    
    if (annotation.points.length > 0) {
      // 绘制连接线
      if (annotation.points.length > 1) {
        const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline')
        const points = annotation.points.map(p => `${p.x},${p.y}`).join(' ')
        
        polyline.setAttribute('points', points)
        polyline.setAttribute('fill', 'none')
        polyline.setAttribute('stroke', annotation.color)
        polyline.setAttribute('stroke-width', lineWidth.value)
        polyline.style.pointerEvents = 'auto'
        polyline.style.cursor = 'pointer'
        
        svg.appendChild(polyline)
        
        // 如果有3个或更多点，显示闭合预览线（连接最后一个点到第一个点）
        if (annotation.points.length >= 3) {
          const closingLine = document.createElementNS('http://www.w3.org/2000/svg', 'line')
          const firstPoint = annotation.points[0]
          const lastPoint = annotation.points[annotation.points.length - 1]
          
          closingLine.setAttribute('x1', lastPoint.x)
          closingLine.setAttribute('y1', lastPoint.y)
          closingLine.setAttribute('x2', firstPoint.x)
          closingLine.setAttribute('y2', firstPoint.y)
          closingLine.setAttribute('stroke', annotation.color)
          closingLine.setAttribute('stroke-width', lineWidth.value)
          closingLine.setAttribute('stroke-dasharray', '5,5') // 虚线表示预览
          closingLine.setAttribute('opacity', '0.7')
          closingLine.style.pointerEvents = 'none'
          
          svg.appendChild(closingLine)
        }
      }
      
      // 添加点标记
      annotation.points.forEach((point, index) => {
        const pointElement = document.createElement('div')
        pointElement.className = `line-point point-${index}`
        pointElement.style.cssText = `
          position: absolute;
          left: ${point.x - 4}px;
          top: ${point.y - 4}px;
          width: 8px;
          height: 8px;
          background: white;
          border: 2px solid ${annotation.color};
          border-radius: 50%;
          cursor: pointer;
          pointer-events: auto;
          z-index: ${annotation.zIndex + 1};
        `
        
        // 为第一个点添加特殊样式，表示可以点击闭合
        if (index === 0 && annotation.points.length >= 3) {
          pointElement.style.background = annotation.color
          pointElement.style.boxShadow = '0 0 8px rgba(0,0,0,0.3)'
          pointElement.title = '点击此点完成多边形绘制'
          
          // 添加点击事件处理
          pointElement.addEventListener('click', (e) => {
            e.preventDefault()
            e.stopPropagation()
            console.log('[AnnotationDrawer] 点击第一个点，完成多边形绘制')
            finishLinePolygonDrawing()
          })
        }
        
        container.appendChild(pointElement)
      })
      
      // 添加标签
      if (!container.querySelector('.annotation-label') && annotation.points.length > 0) {
        const label = document.createElement('div')
        label.className = 'annotation-label'
        label.textContent = annotation.displayText || annotation.title
        label.style.cssText = `
          position: absolute;
          top: ${annotation.points[0].y - 24}px;
          left: ${annotation.points[0].x}px;
          padding: 2px 6px;
          background: ${annotation.color};
          color: white;
          font-size: 12px;
          border-radius: 4px;
          white-space: nowrap;
          user-select: none;
          pointer-events: none;
          z-index: ${annotation.zIndex + 1};
        `
        container.appendChild(label)
      }
    }
  }
  
  /**
   * 完成线段多边形绘制
   */
  const finishLinePolygonDrawing = () => {
    if (!currentDrawing.value || currentDrawing.value.points.length < 2) {
      if (currentDrawing.value) {
        console.log('[AnnotationDrawer] 线段点数不足，移除:', currentDrawing.value.points.length)
        removeAnnotationElement(currentDrawing.value.id)
      }
      currentDrawing.value = null
      isDrawing.value = false
      return
    }
    
    console.log('[AnnotationDrawer] 完成线段多边形绘制，点数:', currentDrawing.value.points.length)
    
    // 移除临时绘制元素，重新创建完成的线段多边形元素
    removeAnnotationElement(currentDrawing.value.id)
    createCompletedLinePolygonElement(currentDrawing.value)
    
    // 添加到标注列表
    addAnnotation(currentDrawing.value)
    
    currentDrawing.value = null
    isDrawing.value = false
  }
  
  /**
   * 创建完成的线段多边形元素
   * @param {object} annotation - 标注数据
   */
  const createCompletedLinePolygonElement = (annotation) => {
    if (!overlayElement) return
    
    const container = document.createElement('div')
    container.id = `annotation-${annotation.id}`
    container.className = 'annotation-line-polygon-completed'
    container.style.cssText = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: ${annotation.zIndex};
    `
    
    // 创建SVG元素
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    svg.style.cssText = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
    `
    
    // 创建封闭的多边形（自动连接首尾）
    const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon')
    const points = annotation.points.map(p => `${p.x},${p.y}`).join(' ')
    
    polygon.setAttribute('points', points)
    polygon.setAttribute('fill', hexToRgba(annotation.color, 0.2))
    polygon.setAttribute('stroke', annotation.color)
    polygon.setAttribute('stroke-width', lineWidth.value)
    polygon.setAttribute('fill-rule', 'evenodd')
    polygon.setAttribute('class', 'annotation-shape') // 添加统一的 class
    polygon.style.cursor = 'pointer'
    polygon.style.pointerEvents = 'none' // 图形本身不捕获事件
    
    svg.appendChild(polygon)
    container.appendChild(svg)
    
    // 添加连接点
    annotation.points.forEach((point, index) => {
      const connectionPoint = document.createElement('div')
      connectionPoint.className = `annotation-vertex vertex-${index}`
      connectionPoint.style.cssText = `
        position: absolute;
        left: ${point.x - 4}px;
        top: ${point.y - 4}px;
        width: 8px;
        height: 8px;
        background: white;
        border: 2px solid ${annotation.color};
        border-radius: 50%;
        cursor: pointer;
        pointer-events: auto; /* 角点需要能被点击 */
        z-index: ${annotation.zIndex + 1};
      `
      container.appendChild(connectionPoint)
    })
    
    // 添加标签
    const label = document.createElement('div')
    label.className = 'annotation-label'
    label.textContent = annotation.displayText || annotation.title
    label.style.cssText = `
      position: absolute;
      top: ${annotation.points[0].y - 24}px;
      left: ${annotation.points[0].x}px;
      padding: 2px 6px;
      background: ${annotation.color};
      color: white;
      font-size: 12px;
      border-radius: 4px;
      white-space: nowrap;
      user-select: none;
      pointer-events: none;
      z-index: ${annotation.zIndex + 1};
    `
    
    container.appendChild(label)
    overlayElement.appendChild(container)
    
    console.log('[AnnotationDrawer] 完成线段多边形元素已创建:', annotation.id, '顶点数:', annotation.points.length)
  }
  
  /**
   * 移除标注DOM元素
   * @param {string} annotationId - 标注ID
   */
  const removeAnnotationElement = (annotationId) => {
    const element = overlayElement?.querySelector(`#annotation-${annotationId}`)
    if (element) {
      element.remove()
    }
  }
  
  /**
   * 添加标注到列表
   * @param {object} annotation - 标注数据
   */
  const addAnnotation = (annotation) => {
    annotations.value.push(annotation)
    console.log('[AnnotationDrawer] 标注已添加:', annotation)
    
    // 触发标注完成回调
    if (typeof onAnnotationComplete === 'function') {
      onAnnotationComplete(annotation)
    }
  }
  
  /**
   * 删除标注
   * @param {string} annotationId - 标注ID
   */
  const removeAnnotation = (annotationId) => {
    const index = annotations.value.findIndex(ann => ann.id === annotationId)
    if (index > -1) {
      annotations.value.splice(index, 1)
      removeAnnotationElement(annotationId)
    }
  }
  
  /**
   * 清空所有标注
   */
  const clearAllAnnotations = () => {
    // 清除内存中的标注数据
    annotations.value.forEach(annotation => {
      removeAnnotationElement(annotation.id)
    })
    annotations.value = []
    
    // 强制清除DOM中的所有标注元素（防止遗漏）
    if (overlayElement) {
      const allAnnotationElements = overlayElement.querySelectorAll('[id^="annotation-"]')
      allAnnotationElements.forEach(element => {
        element.remove()
      })
      console.log(`[AnnotationDrawer] 强制清除了 ${allAnnotationElements.length} 个DOM标注元素`)
    }
  }
  
  /**
   * 设置标注模式
   * @param {string} mode - 标注模式
   */
  const setAnnotationMode = (mode) => {
    // 取消当前绘制
    if (currentDrawing.value) {
      removeAnnotationElement(currentDrawing.value.id)
      currentDrawing.value = null
      isDrawing.value = false
    }
    
    annotationMode.value = mode
  }
  
  /**
   * 设置当前类别
   * @param {object} category - 类别对象
   */
  const setCurrentCategory = (category) => {
    currentCategory.value = category
  }
  
  /**
   * 设置线条宽度
   * @param {number} width - 线条宽度
   */
  const setLineWidth = (width) => {
    lineWidth.value = width
  }
  
  /**
   * 标注完成回调函数
   */
  let onAnnotationComplete = null
  
  /**
   * 设置标注完成回调
   * @param {function} callback - 回调函数
   */
  const setOnAnnotationComplete = (callback) => {
    onAnnotationComplete = callback
  }
  
  /**
   * 重新渲染现有标注
   * @param {Array} existingAnnotations - 现有标注数据数组
   * @param {Array} categories - 类别数据数组，用于获取颜色信息
   */
  const renderExistingAnnotations = (existingAnnotations) => {
    if (!existingAnnotations || !Array.isArray(existingAnnotations)) return
    
    console.log('[AnnotationDrawer] 渲染现有标注:', existingAnnotations.length, '个')
    
    // 获取已存在的标注元素IDs和数据中的标注IDs
    const existingElementIds = new Set()
    const dataAnnotationIds = new Set(existingAnnotations.map(ann => ann.id))
    
    if (overlayElement) {
      const existingElements = overlayElement.querySelectorAll('[id^="annotation-"]')
      existingElements.forEach(el => {
        const id = el.id.replace('annotation-', '')
        existingElementIds.add(id)
        
        // 如果DOM中的元素在数据中不存在，删除孤立元素
        if (!dataAnnotationIds.has(id)) {
          console.log('[AnnotationDrawer] 删除孤立的标注元素:', id)
          el.remove()
        }
      })
    }
    
    existingAnnotations.forEach(annotation => {
      // 如果标注元素已经存在，跳过渲染
      if (existingElementIds.has(annotation.id)) {
        console.log('[AnnotationDrawer] 标注已存在，跳过渲染:', annotation.id)
        return
      }
      
      console.log('[AnnotationDrawer] 渲染新标注:', annotation.type, annotation.id)
      
      // 确保有默认颜色
      if (!annotation.color) {
        annotation.color = '#409EFF'
      }
      if (!annotation.title) {
        annotation.title = '标注'
      }
      
      if (annotation.type === 'rectangle') {
        createCompletedRectangleElement(annotation)
      } else if (annotation.type === 'line-polygon') {
        createCompletedLinePolygonElement(annotation)
      } else if (annotation.type === 'point') {
        // 对于旧的点标注，转换为点元素显示
        createPointElement(annotation)
      }
    })
  }
  
  /**
   * 创建简单点标注元素（兼容旧数据）
   * @param {object} annotation - 标注数据
   */
  const createPointElement = (annotation) => {
    if (!overlayElement) return
    
    const element = document.createElement('div')
    element.id = `annotation-${annotation.id}`
    element.className = 'annotation-point-simple annotation-shape'
    element.style.cssText = `
      position: absolute;
      left: ${(annotation.x || 0) - 8}px;
      top: ${(annotation.y || 0) - 8}px;
      width: 16px;
      height: 16px;
      border: 3px solid ${annotation.color || '#409EFF'};
      background: white;
      border-radius: 50%;
      cursor: pointer;
      pointer-events: none; /* 图形本身不捕获事件 */
      z-index: ${annotation.zIndex || 1};
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    `
    
    // 添加标签
    const label = document.createElement('div')
    label.className = 'annotation-label'
    label.textContent = annotation.displayText || annotation.title || '点标注'
    label.style.cssText = `
      position: absolute;
      top: -30px;
      left: -20px;
      padding: 2px 6px;
      background: ${annotation.color || '#409EFF'};
      color: white;
      font-size: 12px;
      border-radius: 4px;
      white-space: nowrap;
      user-select: none;
      text-align: center;
      min-width: 40px;
      pointer-events: none;
    `
    
    element.appendChild(label)
    overlayElement.appendChild(element)
  }
  
  /**
   * 清理资源
   */
  const cleanup = () => {
    removeEventListeners()
    clearAllAnnotations()
    imageContainer = null
    imageElement = null
    overlayElement = null
  }
  
  return {
    // 状态
    annotationMode,
    currentCategory,
    lineWidth,
    annotations,
    isDrawing,
    
    // 方法
    initialize,
    setAnnotationMode,
    setCurrentCategory,
    setLineWidth,
    setOnAnnotationComplete,
    addAnnotation,
    removeAnnotation,
    clearAllAnnotations,
    renderExistingAnnotations,
    cleanup
  }
}